package com.des1gn.ymgetil.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.joda.time.DateTime;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class JwtUtil {

    public static String getNewSessionId(String sessionId,String mxid){
        System.out.println(JWTUtil.verify(sessionId,"9Z".getBytes()));
        JWT jwt = JWTUtil.parseToken(sessionId);
        String val = jwt.getPayload("val").toString();
        String c = val.substring(val.indexOf("\r\n")).replaceAll("A","").replaceAll("=","");
        String[] split = val.split("\\\r\n");
        System.out.println(c);
        String s = Base64.decodeStr(c);
        System.out.println(s);
        s = s+" \u0010"+mxid+"\u0001";
        String i = Base64.encode(s).replaceAll("=","")+"AAAA";
        String n = split[0]+"\r\n"+new String(i).substring(0,i.length()-11)+"\r\n"+new String(i).substring(i.length()-11);
        System.out.println(n);
//        Long unix = Long.valueOf(new BigDecimal(System.currentTimeMillis()).divide(new BigDecimal(1000)).toString()+"0000");
////        System.out.println(unix);
        Long unix = System.currentTimeMillis()/1000L;
//        jwt.setPayload("iat",unix);
//        jwt.setPayload("exp",unix);
//        jwt.setPayload("jti", DateTime.now().toString("yyyyMMddHHmmss"));
//        jwt.setPayload("val",n);
        Map<String,Object> headers = new LinkedHashMap<>();
        headers.put("typ",jwt.getHeader("typ"));
        headers.put("alg",jwt.getHeader("alg"));
        Map<String,Object> payload = new LinkedHashMap<>();
        payload.put("iat",jwt.getPayload("iat"));
        payload.put("exp",jwt.getPayload("exp"));
        payload.put("sub",jwt.getPayload("sub"));
        payload.put("jti",jwt.getPayload("jti"));
        payload.put("val",jwt.getPayload("val"));
        String token = JWTUtil.createToken(headers, payload,"HS256".getBytes());
        JWT jwt1 = JWTUtil.parseToken(token);
//        System.out.println(token);
        return token;
    }



}
